#include"../../inc/threadpool/Thread.h"
#include<iostream>
#include<functional>
#include<string>
#include<pthread.h>
#include<unistd.h>

using std::string;

namespace SE
{
    Thread::Thread(ThreadCallBack&& cb)
    : _pid(0), _isRunning(false), _cb(std::move(cb))
    {}

    Thread::~Thread()
    {
        if(_isRunning)
        {
            if(pthread_detach(_pid))
            {
                perror("pthread_detach");
                return;
            }
            _isRunning = false;
        }
    }

    void Thread::start()
    {
        if(!_isRunning)
        {
            if(pthread_create(&_pid, nullptr, func, this))
                logError("pthread_create");
            _isRunning = true;
        }
    }

    void Thread::join()
    {
        if(_isRunning)
        {
            if(pthread_join(_pid, nullptr))
                logError("pthread_join");
            _isRunning = false;
        }
    }

    void* Thread::func(void* arg)
    {
        Thread* p = static_cast<Thread*>(arg);
        p->_cb();
        return nullptr;
    }

} // namespace 